<template>
    <div class="pagebody">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> {{ modelTitle }} </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="search-box">
                <el-form :inline="true">
                    <template v-if="model.searchOption">
                        <el-form-item :label="item.name" v-for="(item, index) in model.searchOption" :key="index">
                            <el-input
                                v-model="searchSet[item.key]"
                                v-if="!item.inputType || item.inputType == 'text'"
                                v-bind="Object.assign({}, item.inputAttrs)"
                                prefix-icon="el-icon-search"
                                clearable
                                placeholder="请输入搜索信息"
                            ></el-input>
                            <el-select
                                v-model="searchSet[item.key]"
                                clearable
                                v-else-if="item.inputType == 'select'"
                                v-bind="Object.assign({}, { placeholder: '请输入搜索信息' }, item.inputAttrs)"
                            >
                                <el-option v-for="o in item.inputOptions" :key="o.value" :label="o.label" :value="o.value"> </el-option>
                            </el-select>
                        </el-form-item>
                    </template>
                    <el-button type="primary" v-if="model.searchOption" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                    <el-button type="primary" v-else icon="el-icon-refresh" @click="handleRefresh">重新加载</el-button>
                    <el-button
                        type="primary"
                        v-if="!model.operation || model.operation.ADD != false"
                        icon="el-icon-plus"
                        @click="handleAddNew"
                        >新建</el-button
                    >
                </el-form>
            </div>
            <el-table :data="tableData" v-loading="tableLoading" border class="table" ref="mainTable" header-cell-class-name="table-header">
                <template v-for="(item, index) in model.archetype">
                    <el-table-column
                        :key="index"
                        :prop="item.key"
                        :label="item.name"
                        v-if="item.columnHidden != true"
                        v-bind="Object.assign({}, item.columnAttrs)"
                        align="center"
                    ></el-table-column>
                </template>
                <!-- <el-table-column type="selection"
                         width="55"
                         align="center"></el-table-column> -->
                <el-table-column
                    v-if="!model.operation || model.operation.EDIT != false || model.operation.DELETE != false"
                    label="操作"
                    min-width="140"
                    align="center"
                >
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            v-if="!model.operation || model.operation.EDIT != false"
                            @click="handleEdit(scope.$index, scope.row)"
                            >编辑</el-button
                        >
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            v-if="!model.operation || model.operation.DELETE != false"
                            class="color-red"
                            @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination" v-if="model.classifyPage == true">
                <el-pagination
                    background
                    layout="sizes, total, prev, pager, next"
                    :current-page="query.index"
                    :page-sizes="[10, 20, 30, 40, 50, 100]"
                    :page-size="query.pageSize"
                    :total="itemTotal"
                    @current-change="handlePageChange"
                    @size-change="handlePageSizeChange"
                ></el-pagination>
            </div>
        </div>

        <el-dialog :title="editIsNewAdd ? '新建' : '编辑'" v-dialogDrag center :visible.sync="editVisible" v-if="editVisible" width="60%">
            <el-form ref="form" :model="form" :rules="model.formRules" label-width="120px">
                <template v-for="(item, index) in model.archetype">
                    <el-form-item :label="item.name" :key="index" :prop="item.key" v-if="item.editHidden != true">
                        <el-input
                            v-model="form[item.key]"
                            v-if="!item.inputType || item.inputType == 'text'"
                            v-bind="Object.assign({}, { 'show-word-limit': true }, item.inputAttrs)"
                        ></el-input>
                        <el-select
                            v-model="form[item.key]"
                            v-else-if="item.inputType == 'select'"
                            v-bind="Object.assign({}, {}, item.inputAttrs)"
                        >
                            <el-option v-for="o in item.inputOptions" :key="o.value" :label="o.label" :value="o.value"> </el-option>
                        </el-select>
                        <el-input-number
                            v-model="form[item.key]"
                            v-else-if="item.inputType == 'number'"
                            v-bind="Object.assign({}, {}, item.inputAttrs)"
                        ></el-input-number>
                        <!-- <restfulModelInput :inputType="item.inputType" /> -->
                    </el-form-item>
                </template>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import API from '../../../api/index'; //读入restfulAPI
import Model from '../../../restfulModel/standardTable'; //读入model
import dataTable from './dataTable';
// import restfulModelInput from '../../../restfulModel/restfulModelInput.vue'
export default {
    name: 'restfulModelTable',
    mixins: [dataTable],
    components: {
        // restfulModelInput,
    },
    data() {
        return {
            searchSet: {},
            query: {
                status: 1
            },
            modelKey: null,
            modelTitle: '',
            model: { apiKey: null, classifyPage: false, archetype: [] },
            editVisible: false,
            editIsNewAdd: false,
            form: {}
        };
    },
    created() {
        this.init();
    },
    watch: {
        $route(to, from) {
            // 对路由变化作出响应...
            if (to.path.endsWith('restfulModelTable')) {
                this.init();
            }
        }
    },
    methods: {
        //页面初始化
        init() {
            this.modelKey = this.$route.query.modelKey;
            if (this.modelKey) {
                this.model = Model[this.modelKey];
                this.modelTitle = this.model.tableTitle;
                if (this.model.searchOption) this.searchKey = this.model.searchOption[0].key;
                this.getData();
            } else {
                this.$message.error(`参数异常`);
            }
        },

        getData() {
            this.tableLoading = true;
            API.StandardDoWith(API[this.model.apiKey].Get(this.getQuery()), this, {
                success: (detail) => {
                    if (this.model.classifyPage == true) {
                        this.itemTotal = detail.count;
                        this.tableData = detail.list;
                    } else {
                        this.tableData = detail;
                    }
                },
                complete: () => {
                    this.tableLoading = false;
                }
            });
        },
        handleAddNew() {
            this.editVisible = true;
            this.editIsNewAdd = true;

            let obj = {};
            this.model.archetype.map((archetype) => {
                if (archetype.default != undefined) {
                    obj[archetype.key] = archetype.default;
                }
            });

            this.form = obj;
        },
        requestAddNew(data) {
            API.StandardDoWith(API[this.model.apiKey].Post(data), this, {
                loading: '新增处理中',
                success: (detail) => {
                    this.editVisible = false;
                    this.$message.success(`新增数据成功`);
                    this.getData();
                }
            });
        },
        requestModify(data) {
            API.StandardDoWith(API[this.model.apiKey].Put(data), this, {
                loading: '修改处理中',
                success: (detail) => {
                    this.editVisible = false;
                    this.$message.success(`修改数据成功`);
                    this.getData();
                }
            });
        },
        requestDelete(params) {
            //计算是否为删除表格最后一页的单项，进行自动回退页面
            let autoBackPrevPage = false;
            if (this.query.index > 1 && this.itemTotal % this.query.pageSize == 1) {
                let sumPageCount = Math.ceil(this.itemTotal / this.query.pageSize);
                if (this.query.index == sumPageCount) {
                    autoBackPrevPage = true;
                }
            }

            API.StandardDoWith(API[this.model.apiKey].Delete(params), this, {
                loading: '删除处理中',
                success: (detail) => {
                    this.$message.success(`删除数据成功`);
                    if (autoBackPrevPage) {
                        this.$set(this.query, 'index', this.query.index - 1);
                    }
                    this.getData();
                }
            });
        },

        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.requestDelete({ id: row.id });
                })
                .catch(() => {});
        },

        // 编辑操作
        handleEdit(index, row) {
            this.form = Object.assign({}, row); //仅单层拷贝
            this.editVisible = true;
            this.editIsNewAdd = false;
        },
        // 保存编辑
        saveEdit() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.editIsNewAdd) {
                        this.requestAddNew(this.form);
                    } else {
                        this.requestModify(this.form);
                    }
                } else {
                    this.$message.error(`表单验证失败，无法提交`);
                    return false;
                }
            });
        }
    }
};
</script>

<style scoped>
@import '../../../assets/css/dataTable.css';
</style>
